package com.atguigu.service.impl;

import com.atguigu.mapper.SysRoleMapper;
import com.atguigu.mapper.SysUserRoleMapper;
import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.service.SysUserRoleService;
import com.atguigu.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Override
    public Map<String, Object> toAssign(Integer userId) {
        //1.获取所有角色
        List<SysRole> sysRoles = sysRoleMapper.selectList(null);
        //2.获取当前用户已分配的角色
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> existSysUserRoles = sysUserRoleMapper.selectList(lambdaQueryWrapper);
        List<Long> rolesIds = existSysUserRoles.stream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());
        List<SysRole> resultRoles=new ArrayList<>();
        for (SysRole sysRole : sysRoles) {
            if (rolesIds.contains(sysRole.getId())) resultRoles.add(sysRole);
        }
        Map<String, Object> resultMap=new HashMap<>();
        resultMap.put("assignRoleList", resultRoles);
        resultMap.put("allRolesList", sysRoles);
        return resultMap;
    }

    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //先删除用户之前分配的所有角色
        LambdaQueryWrapper<SysUserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleMapper.delete(wrapper);
        //然后为用户重新分配角色
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        Long userId = assginRoleVo.getUserId();
        if (!CollectionUtils.isEmpty(roleIdList)){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            for (Long roleId : roleIdList) {
                sysUserRole.setRoleId(roleId);
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
    }
}
